package com.styytech.dadabao.widge.clippicture;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

import com.styytech.dadabao.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public abstract class CameraBaseActivity extends ConstantsActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 设置临时存储获取照片的临时路径
        setPhotoTempPath(setSaveTempPhotoPath());
        super.onCreate(savedInstanceState);
    }

    /**
     * 设置临时存储获取照片的临时路径（包括图片文件名）<br>
     * 默认是路径是sd卡根目录dada/images/headImg.jpg
     */
    public abstract String setSaveTempPhotoPath();

    /**
     * 成功返回图片的事件监听<br>
     * 处理（填充）传进的图片<br>
     * 该方法在调用系统相机获取到图片后回调<br>
     *
     * @param photo 照片（bitmap）
     */
    public abstract void disposePicture(Bitmap photo);

    /**
     * 设置需要跳转到自定义截图界面的<br>
     * 如果不需要跳转到自定义截图界面，返回null即可
     */
    public abstract Class skipClipActivityName();

    /**
     * 显示按钮(默认的自定义显示效果)
     * 用户可以根据自己的显示效果重写
     *
     * @param context 上下文
     * @param view    显示的布局
     */
    public void showCameraDialog(Context context, View view) {

        Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(
                context, R.anim.feedback_menushow);
        view.startAnimation(hyperspaceJumpAnimation);
        view.setVisibility(View.VISIBLE);

    }

    /**
     * 隐藏按钮(默认的自定义隐藏效果)
     * 用户可以根据自己的隐藏效果重写
     *
     * @param context 上下文
     * @param view    隐藏的布局
     */
    public void hideCameraDialog(Context context, View view) {

        Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(
                context, R.anim.feedback_menuhide);
        view.startAnimation(hyperspaceJumpAnimation);
        view.setVisibility(View.GONE);
    }

    /**
     * 拍照后获取图片<br>
     * requestCode == CAMERA_REQUEST_CODE 跳转到系统截图界面<br>
     * requestCode == PIC_REQUEST_FROM_CAMERA 跳转到自定义截图界面<br>
     * requestCode == PIC_TAKE_FROM_CAMERA 字节打开图片
     */
    public void takePhoto(int requestCode) {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(new File(getPhotoTempPath())));
            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            startActivityForResult(intent, requestCode);
        } else {
            // 请确认已经插入SD卡
        }
    }

    // 从相册拿照片

    /**
     * requestCode == PIC_REQUEST_FROM_LOCAL 跳转到自定义截图界面 <br>
     * requestCode == IMAGE_REQUEST_CODE 跳转到系统截图界面<br>
     * requestCode == PIC_GET_FROM_CAMERA 直接从相册选取的图片
     */
    public void getPhoto(int requestCode) {
        Intent intent = new Intent();
        /* 开启Pictures画面Type设定为image */
        intent.setType("image/*");
        /* 使用Intent.ACTION_GET_CONTENT这个Action */
        intent.setAction(Intent.ACTION_GET_CONTENT);
        /* 取得相片后返回本画面 */
        startActivityForResult(intent, requestCode);
    }

    /**
     * 复写onActivityResult，这个方法 是要等到SimpleTaskActivity点了提交过后才会执行的
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            Bitmap photo = null;
            switch (requestCode) {
                case PIC_TAKE_FROM_CAMERA: // 拍照返回
                    photo = takePictureResultOriginal();
                    disposePicture(photo);
                    break;
                case PIC_GET_FROM_CAMERA: // 相册返回
                    photo = getPictureResultOriginal(data);
                    disposePicture(photo);
                    break;
                case PIC_REQUEST_FROM_CAMERA: // 拍照后返回
                    takePictureResult();
                    break;
                case PIC_REQUEST_FROM_LOCAL: // 本地目录选取后返回
                    getPictureResult(data);
                    break;
                case PIC_REQUEST_CLIPPICTURE: // 本地目录选取后截图后的返回
                    disposePicture(getHeadimg(data));
                    break;
                case CAMERA_REQUEST_CODE:
                    clipPictureRequest(Uri.fromFile(new File(getPhotoTempPath())));
                    break;
                case IMAGE_REQUEST_CODE:
                    clipPictureRequest(data.getData());
                    break;
                case RESULT_REQUEST_CODE: // 图片缩放完成后
                    if (data != null) {
                        photo = getImageToView(data);
                        disposePicture(photo);
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 拍照完成后，跳转到截图的界面
     */
    public void takePictureResult() {
        Bitmap bitmap = BitmapFactory.decodeFile(getPhotoTempPath());
        skipClipView(bitmap);
    }

    /**
     * 从相册中选取照片后，跳转到截图的界面
     *
     * @param data
     */
    public void getPictureResult(Intent data) {
        Uri uri1 = data.getData();
        ContentResolver cr = this.getContentResolver();

        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri1));
            skipClipView(bitmap);
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void clipPictureRequest(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 480);
        intent.putExtra("outputY", 480);
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param data
     */
    public Bitmap getImageToView(Intent data) {
        Bundle extras = data.getExtras();
        Bitmap photo = null;
        if (extras != null) {
            photo = extras.getParcelable("data");
        }
        return photo;
    }

    private Bitmap getHeadimg(Intent data) {
        Bitmap photo = null;
        if (data != null) {
            photo = BitmapFactory.decodeFile(getPhotoTempPath());
        }
        return photo;

    }

    /**
     * 最高质量头像截图
     *
     * @param bitmap
     */
    public void skipClipView(Bitmap bitmap) {
        saveBitmap(bitmap, 100);
        Intent intent = new Intent();
        intent.setClass(this, skipClipActivityName());
        startActivityForResult(intent, PIC_REQUEST_CLIPPICTURE);
    }

    /**
     * 拍照完成后，未经过截图处理的方法
     */
    public Bitmap takePictureResultOriginal() {
        FileInputStream fis = null;
        Bitmap photo = null;
        try {
            fis = new FileInputStream(getPhotoTempPath());
            photo = new BitmapDrawable(fis).getBitmap();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        return photo;
    }

    /**
     * 从相册中选取照片后，未经过截图的方法
     *
     * @param data
     */
    public Bitmap getPictureResultOriginal(Intent data) {
        Uri uri1 = data.getData();
        ContentResolver cr = this.getContentResolver();
        Bitmap photo = null;
        try {
            photo = BitmapFactory.decodeStream(cr.openInputStream(uri1));
        } catch (FileNotFoundException e) {
            // 获取图片失败
        }
        return photo;
    }


}
